<template>
  <div>
    <el-card>
      <CategorySelector :isShowList = "isShowList" @changeCategory="changeCategory"></CategorySelector>
    </el-card>

    <el-card style="margin-top:20px">
      <!-- 列表页面 -->
      <div v-show="isShowList">
        <el-button
          type="primary"
          icon="el-icon-plus"
          :disabled="!category3Id"
          @click="showAddDiv"
        >添加属性</el-button>
        <el-table
          border
          :data="attrList"
          style="width: 100%"
        >
          <el-table-column
            type="index"
            align="center"
            prop="prop"
            label="序号"
            width="80"
          ></el-table-column>

          <el-table-column
            prop="attrName"
            label="属性名称"
            width="150"
          ></el-table-column>

          <el-table-column
            prop="prop"
            label="属性值列表"
            width="width"
          >
            <template slot-scope="{row}">
              <el-tag
                type="danger"
                v-for="(attrValue) in row.attrValueList"
                :key="attrValue.id"
              >{{attrValue.valueName}}</el-tag>
            </template>
          </el-table-column>

          <el-table-column
            prop="prop"
            label="操作"
            width="150"
          >
            <template slot-scope="{row}">
              <HintButton
                type="warning"
                size="mini"
                icon="el-icon-edit"
                title="修改"
                @click="showUpdateDiv(row)"
              ></HintButton>
              <el-popconfirm
                  @onConfirm="deleteAttr(row)"
                  :title="`你确定删除${row.attrName}吗?`"
                >
              <HintButton
              slot="reference"
                type="danger"
                size="mini"
                title="删除"
                icon="el-icon-delete"
              >
                
              </HintButton>
                </el-popconfirm>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <!-- 添加或者修改 -->
      <div v-show="!isShowList">
        <el-form
          :inline="true"
          :model="attrForm"
        >
          <el-form-item label="属性名">
            <el-input
              placeholder="请输入属性名"
              v-model="attrForm.attrName"
            ></el-input>
          </el-form-item>
        </el-form>
        <el-button
          type="primary"
          icon="el-icon-plus"
          @click="addAttrValue"
          :disabled="!attrForm.attrName"
        >添加属性值</el-button>
        <el-button @click="isShowList = true">取消</el-button>
        <el-table
          border
          style="width: 100%; margin:10px 0"
          :data="attrForm.attrValueList"
        >
          <el-table-column
            align="center"
            type="index"
            prop="prop"
            label="序号"
            width="80"
          >
          </el-table-column>
          <el-table-column
            prop="prop"
            label="属性值名称"
            width="width"
          >
            <template slot-scope="{row,$index}">
              <el-input
                :ref="$index"
                v-model="row.valueName"
                placeholder=""
                v-if="row.isEdit"
                @blur="toLook(row)"
                @keyup.enter.native="toLook(row)"
                size="mini"
              ></el-input>
              <span
                style="display:block;width:100%"
                @click="toEdit(row,$index)"
                v-else
              >{{row.valueName}}</span>
            </template>
          </el-table-column>
          <el-table-column
            prop="prop"
            label="操作"
            width="width"
          >
            <template slot-scope="{row,$index}">
              <el-popconfirm
                :title="`确定删除${row.valueName}吗？`"
                @onConfirm="attrForm.attrValueList.splice($index,1)"
              >
                <HintButton
                  slot="reference"
                  size="mini"
                  icon="el-icon-delete"
                  type="danger"
                  title="删除属性值"
                ></HintButton>
              </el-popconfirm>
            </template>

          </el-table-column>

        </el-table>
        <el-button
          type="primary"
          @click="save"
          :disabled = "attrForm.attrValueList.length === 0"
        >保存</el-button>
        <el-button @click="isShowList = true">取消</el-button>
      </div>
    </el-card>
  </div>
</template>

<script>
import cloneDeep from "lodash/cloneDeep";
export default {
  name: "AttrList",
  data() {
    return {
      // data内部不能用this
      category1Id: "",
      category2Id: "",
      category3Id: "",
      attrList: [],
      isShowList: true,

      // 收集数据最终收集成什么样子 是从接口文档来的
      attrForm: {
        attrName: "",
        attrValueList: [
          // {
          //   attrId: 0,
          //   attrName: "",
          //   valueName: "string",
          // },
        ],
        categoryId: 0,
        categoryLevel: 3,
      },
    };
  },
  methods: {
    changeCategory({ categoryId, level }) {
      if (level === 1) {
        // 父组件获取到1级id要清空自己的23级id及属性列表数据
        this.category2Id = "";
        this.category3Id = "";
        this.attrList = [];

        this.category1Id = categoryId;
      } else if (level === 2) {
        // 父组件获取到2级id要清空自己的3级id及属性列表数据

        this.category3Id = "";
        this.attrList = [];

        this.category2Id = categoryId;
      } else if (level === 3) {
        // 父组件获取3级id要请求获取属性列表数据
        this.category3Id = categoryId;
        this.getAttrList();
      }
    },
    // 请求获取属性列表数据
    async getAttrList() {
      let { category1Id, category2Id, category3Id } = this;
      try {
        const result = await this.$API.attr.getList(
          category1Id,
          category2Id,
          category3Id
        );
        if (result.code === 200 || result.code === 20000) {
          this.attrList = result.data;
        }
      } catch (error) {
        this.$message.error("获取失败" + error.message);
      }
    },
    // 点击添加属性按钮显示添加属性页面
    showAddDiv() {
      this.isShowList = false;
      this.attrForm = {
        attrName: "",
        attrValueList: [
          // {
          //   attrId: 0,
          //   attrName: "",
          //   valueName: "string",
          // },
        ],
        categoryId: this.category3Id,
        categoryLevel: 3,
      };
    },
    // 修改数据
    showUpdateDiv(row) {
      this.isShowList = false;
      // 由于属性对象当中属性值列表也是对象属性 那么浅拷贝属性值列表数据还是同一个 所以浅拷贝搞不定对象内部的对象数据
      // this.attrForm = {...row}
      this.attrForm = cloneDeep(row);
      // 修改属性当中 属性值是已经存在的
      this.attrForm.attrValueList.forEach((item) => {
        // item.isEdit = false;
        // item.isEdit = false; isEdit不是响应式的属性 因为一上来data内部没这个属性
        // 这个属性是点击按钮才添加的 此时 数据监视早都结束了 isEdit不可能被监视到 添加的太晚了
        // 他就不是响应式 修改的时候也不会影响到页面
        this.$set(item, "isEdit", false); // 这样添加新的属性才是响应式
      });
    },
    // 点击添加属性值
    addAttrValue() {
      this.attrForm.attrValueList.push({
        attrId: this.attrForm.id, // 当前属性值所属属性的id 添加属性就没有是undefined 修改属性的时候就有
        valueName: "",
        // 由于是新添加的属性值 那么isEdit是true代表目前应该是编辑模式
        isEdit: true,
      });

      // 让新添加的属性值对应的input自动获取焦点
      this.$nextTick(() => {
        this.$refs[this.attrForm.attrValueList.length - 1].focus();
      });
    },
    // 点击span切换为input 切换为编辑模式
    toEdit(row, index) {
      row.isEdit = true;
      // 赋值完成input才开始创建
      this.$nextTick(() => {
        // 让对应的点击这项input自动获取焦点
        this.$refs[index].focus();
      });
    },
    // input失去焦点或者回车事件 切换span 切换查看模式
    toLook(row) {
      // 数据不能为空
      if (row.valueName.trim() === "") {
        row.valueName = "";
        return;
      }
      // 除自己以外 输入的数据是不是和其重复的
      let isRepeat = this.attrForm.attrValueList.some((item) => {
        if (item !== row) {
          return item.valueName === row.valueName;
        }
      });
      if (isRepeat) {
        this.$message.warning("输入的属性值不能重复");
        row.valueName = "";
        return;
      }

      row.isEdit = false;
    },
    // 点击保存
    async save() {
      // 获取请求参数
      let attr = this.attrForm;
      // 整理参数
      // 1、属性值名称如果为空串，从属性值列表当中去除
      // attr.attrValueList = attr.attrValueList.filter(
      //   (item) => item.valueName !== ""
      // );
      // attr.attrValueList.forEach((item) => delete item.isEdit);

      // 2、属性值当中去除isEdit属性
      attr.attrValueList = attr.attrValueList.filter((item) => {
        if (item.valueName !== "") {
          delete item.isEdit;
          return true;
        }
      });

      // 3、属性值列表如果没有属性值，不发请求
      if (attr.attrValueList.length === 0) {
        this.$message.info("属性的属性值列表必须有值");
        return;
      }
      // 发请求
      try {
        // 成功干啥
        const result = await this.$API.attr.addOrUpdate(attr);
        if (result.code === 200 || result.code === 20000) {
          //  提示
          this.$message.success("保存属性成功");
          // 回到列表页
          this.isShowList = true;
          // 重新获取列表页数据
          this.getAttrList();
        }
      } catch (error) {
        // 失败干啥
        this.$message.error("保存属性请求失败");
      }
    },
    // 删除属性
    async deleteAttr(row) {
      try {
        const result = await this.$API.attr.delete(row.id);
        if (result.code === 200 || result.code === 20000) {
          this.$message.success("删除属性成功");
          this.getAttrList();
        } else {
          this.$message.error("删除属性失败");
        }
      } catch (error) {
        this.$message.error("删除属性请求失败" + error.message);
      }
    },
  },
};
</script>

<style scoped>
</style>
